//
//  BFStatusViewController.m
//  13KModel
//
//  Created by jack on 1/09/12.
//  Copyright (c) 2012 __butterfly__. All rights reserved.
//
// CLASS INCLUDES
#import "ATMHud.h"
#import "PubInc.h"
#import "BFStatusView.h"
#import "UIImageView+WebCache.h"
#import "BFStatusViewController.h"

// SYSTEM INCLUDES

// CONST DEFINE 
NSInteger const kColumnPortraitNum = 3;
NSInteger const kColumnLandscape = 4;
CGFloat const kGridItemHight = 160.0f;
CGFloat const kNavigationBarHight = 45.0f;

@interface BFStatusViewController ()

- (void)initPageAttr;
- (void)initNavBar;
- (void)initPsCollect;
- (void)initAdvBanner;

- (void)dataSourceDidLoad;
- (void)dataSourceErrorLoad;
@end

@implementation BFStatusViewController
@synthesize pageIndex, statusList;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 初始化
    [self initPageAttr];
    [self initPsCollect];
    [self initAdvBanner];
    
    // 获取数据
    [self refreshWBStatus];
    [self.view bringSubviewToFront:self.compMessageBox.view];
}

- (void)viewDidUnload
{
    collectionView = nil;
    
    [super viewDidUnload];
}

- (void)resetLayout
{
    if (youMiView) {
        CGRect frame = youMiView.frame;
        frame.origin.y = 0;
        youMiView.frame = frame;
    }
    if (collectionView) {
        CGRect frame = collectionView.frame;
        frame.origin.y = 0;
        collectionView.frame = frame;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self performSelector:@selector(resetLayout) withObject:nil afterDelay:0.5];
}

-(void)loadWBStatusByScreenName:(NSString*)screenName
{
    NSDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                            screenName, @"screen_name", 
                            [NSString stringWithFormat:@"%d", pageIndex], @"page", 
                            @"21", @"count",
                            @"1", @"feature",
                            nil];
    
    // 发送网络请求
    [wbEngine loadRequestWithMethodName:@"statuses/user_timeline.json" 
                             httpMethod:@"GET" 
                                 params:params 
                           postDataType:kWBRequestPostDataTypeNone
                       httpHeaderFields:nil];
    
    // 显示等待效果
    if (pageIndex <= 1) {
        [self startLoadAnimationWithText:NSLocalizedString(@"加载数据", nil)];
    }
}

#pragma mark - private method
- (void)initPageAttr
{
    // 页面设置
    pageIndex = 1;
    statusList = [NSMutableArray array];
    
    // 返回按钮
    [self initNavBar];
    
    // 页面标题
    self.navigationItem.title = [[NSUserDefaults standardUserDefaults] objectForKey:@"title"];
}

- (void)initNavBar
{
    // 返回按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"icon_back.png"] forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(navigateToPrevView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0,
                                button.imageView.image.size.width,
                                button.imageView.image.size.height)];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = backButton;
    
    // 设置按钮
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"icon_setting.png"] forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(gotoSettingView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0,
                                button.imageView.image.size.width,
                                button.imageView.image.size.height)];
    UIBarButtonItem *settingButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = settingButton;
}

- (void)initPsCollect
{
    CGRect frame = CGRectMake(0, kNavigationBarHight,
                              self.view.bounds.size.width,
                              self.view.bounds.size.height-kNavigationBarHight);
    collectionView = [[PullPSCollectionView alloc] initWithFrame:frame];
    [self.view addSubview:collectionView];
    collectionView.collectionViewDelegate   = self;
    collectionView.collectionViewDataSource = self;
    collectionView.pullDelegate             = self;
    collectionView.backgroundColor          = [UIColor clearColor];
    collectionView.numColsPortrait          = kColumnPortraitNum;
    collectionView.numColsLandscape         = kColumnLandscape;
    collectionView.pullDelegate             = self;
}

- (void)initAdvBanner
{
    // Initialize the banner at the top of the screen.
    youMiView = [[YouMiView alloc] initWithContentSizeIdentifier:YouMiBannerContentSizeIdentifier320x50
                                                        delegate:nil];
    youMiView.appID = kGlobalYouMiAdAppID;
    youMiView.appSecret = kGlobalYouMiAdAppSecert;
    youMiView.appVersion = @"1.0";
    youMiView.testing = NO;
    youMiView.delegate = self;
    youMiView.indicateBorder = NO;
    youMiView.indicateTranslucency = NO;
    
    // 开始请求广告
	[youMiView start];
    
    // 设置位置
    CGRect frame = youMiView.frame;
    frame.origin.x = 0;
    frame.origin.y = self.navigationController.navigationBar.frame.size.height;
    youMiView.frame = frame;
    
	[self.view addSubview:youMiView];
}

- (void)dataSourceDidLoad
{
    [collectionView reloadData];
    
    if (collectionView.pullTableIsRefreshing) {
        collectionView.pullTableIsRefreshing = NO;
        collectionView.pullLastRefreshDate = [NSDate date];
    }
    if (collectionView.pullTableIsLoadingMore) {
        collectionView.pullTableIsLoadingMore = NO;
    }
    [self stopLoadAnimation];
}

- (void)dataSourceErrorLoad
{
    [self dataSourceDidLoad];
}

- (void)refreshWBStatus
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [self performSelector:@selector(loadWBStatusByScreenName:)
               withObject:[userDefaults valueForKey:@"screen_name"]
               afterDelay:0.1];
}

- (void)loadMoreWBStatus
{
    self.pageIndex++;
    
    [self refreshWBStatus];
}

#pragma mark- WBEngineDelegate
- (void)engineDidLogIn:(WBEngine *)engine
{
    NSLog(@"engineDidLogIn");
}

- (void)engineNotAuthorized:(WBEngine *)engine
{
    [self dataSourceErrorLoad];
    NSLog(@"engineNotAuthorized");
}

- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
{
    [self showAlertMessageBox:NSLocalizedString(@"亲, 网络不给力啊!", nil)];
}

- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
{
    if ([result isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dict = (NSDictionary *)result;
        NSArray *statuses = [dict objectForKey:@"statuses"];
        for (NSDictionary *status in statuses) {
            NSString *imageurl = [status valueForKey:@"bmiddle_pic"];
            if (imageurl == nil) {
                continue;
            }
            
            [statusList addObject:status];
        }
        [self performSelector:@selector(dataSourceDidLoad) withObject:nil afterDelay:0.1];
    }

    [self dataSourceDidLoad];
}

-(void)engine:(WBEngine *)engine didFailToLogInWithError:(NSError *)error
{
    [self showAlertMessageBox:NSLocalizedString(@"亲, 网络不给力啊!", nil)];
}

#pragma mark- PSCollectionViewDelegate

- (void)collectionView:(PSCollectionView *)collectionView didSelectView:(PSCollectionViewCell *)view atIndex:(NSInteger)index
{
    MWPhotoBrowser *browser = [self.storyboard instantiateViewControllerWithIdentifier:@"Photo"];
    browser.delegate = self;
//    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    [browser setInitialPageIndex:index];
    [self.navigationController pushViewController:browser animated:YES];
}

- (void)gotoSettingView
{
    UIViewController *setting = [self.storyboard instantiateViewControllerWithIdentifier:@"Setting"];
    [self.navigationController pushViewController:setting animated:YES];
}

#pragma mark- PSCollectionViewDataSource

- (NSInteger)numberOfViewsInCollectionView:(PSCollectionView *)collectionView
{
    return [statusList count];
}

- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView viewAtIndex:(NSInteger)index
{
    NSDictionary *status = [statusList objectAtIndex:index];
    BFStatusView *v = (BFStatusView *)[collectionView dequeueReusableView];
    if (!v) {
        v = [[BFStatusView alloc] initWithFrame:CGRectZero];
    }
    
    NSURL *imageUrl = nil;
    NSDictionary *retweeted_status = [status objectForKey:@"retweeted_status"];
    if (retweeted_status) {
        imageUrl = [NSURL URLWithString:[retweeted_status valueForKey:@"bmiddle_pic"]];
    }
    else{
        imageUrl = [NSURL URLWithString:[status valueForKey:@"bmiddle_pic"]];
    }
    
    [v startLoading];
    [v.imageView setImageWithURL:imageUrl placeholderImage:nil options:SDWebImageRetryFailed success:^(UIImage *image) {
        [v stopLoaidng];
    } failure:^(NSError *error) {
        [v stopLoaidng];
    }];
    return v;
}

- (CGFloat)heightForViewAtIndex:(NSInteger)index
{
    return kGridItemHight;
}

#pragma mark- MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return statusList.count;
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    NSDictionary *status = [statusList objectAtIndex:index];
    NSDictionary *retweeted_status = [status objectForKey:@"retweeted_status"];
    if (retweeted_status) {
        return [MWPhoto photoWithURL:[NSURL URLWithString:[retweeted_status valueForKey:@"original_pic"]]];
    }
    else{
        return [MWPhoto photoWithURL:[NSURL URLWithString:[status valueForKey:@"original_pic"]]];
    }
}

#pragma mark - PullPSCollectionViewDelegate

- (void)pullPsCollectionViewDidTriggerRefresh:(PullPSCollectionView*)pullTableView
{
    [self performSelector:@selector(refreshWBStatus) withObject:nil afterDelay:1.0f];
}

- (void)pullPsCollectionViewDidTriggerLoadMore:(PullPSCollectionView*)pullTableView
{
    [self performSelector:@selector(loadMoreWBStatus) withObject:nil afterDelay:1.0f];
}

#pragma mark - YouMiDelegate

@end
